//
//  AddCarViewController.m
//  Audit
//
//  Created by cc on 15-2-11.
//  Copyright (c) 2015年 cc. All rights reserved.
//

#import "AddCarViewController.h"
//#import "Car.h"
#import "ConditionViewController.h"
#import "AppDelegate.h"
#import <AVFoundation/AVFoundation.h>
#import "GetVinViewController.h"

@interface AddCarViewController ()<UITextFieldDelegate>
{
    IBOutlet UIButton *btnSeries;//生产车型
    IBOutlet UIButton *btnModel;//生产配置
    IBOutlet UITextField *txtVin;//VIN
    IBOutlet UITextField *txtTransmission;//变速箱
    IBOutlet UITextField *txtColor;//颜色
    IBOutlet UITextField *txtDriveDirection;//驾驶方向
    IBOutlet UITextField *txtDefect_Info;//重点缺陷
    IBOutlet UITextField *txtRepair_Info;//返修信息
    
    IBOutlet UITextField *txtEngine          ;//引擎
    IBOutlet UIButton *btnPlant   ;//检查地点
    IBOutlet UIButton *btnDomain ;//生产基地
    IBOutlet UIButton *btnAuditGroup     ;//检查组
    IBOutlet UITextField *txtShiftDate      ;//检查日期
    IBOutlet UITextField *txtBuildDate    ;//生产日期
    IBOutlet UITextField *txtCsn     ;//生产序号
    IBOutlet UIButton *btnPhase    ;//生产阶段
    
    IBOutlet UIView *container;
}
@end

@implementation AddCarViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
    
    [[NSNotificationCenter defaultCenter]  addObserver:self selector:@selector(setNoNetWork:) name:NOTIFICATION_NO_NETWORK object:nil];//设置当前网络状态
    
    [[NSNotificationCenter defaultCenter]  addObserver:self selector:@selector(setInitData) name:NOTIFICATION_INIT_DATA object:nil];//加载数据完成后初始化控件
    
    //使用NSNotificationCenter 鍵盤出現時
    [[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(keyboardWasShown:)
                                                 name:UIKeyboardDidShowNotification object:nil];
    
    //使用NSNotificationCenter 鍵盤隐藏時
    [[NSNotificationCenter defaultCenter] addObserver:self
     
                                             selector:@selector(keyboardWillBeHidden:)
                                                 name:UIKeyboardWillHideNotification object:nil];
    
    [self setNavTitle:@"添加车辆"];
    [self setNavBackButton:nil];
    [self setNavRightButton:@"关闭"];
    
    [self initDicList];
}

#pragma mark -
#pragma mark notification Methods
- (void)setNoNetWork:(id)sender
{
    AppDelegate *delegate=(AppDelegate*)[[UIApplication sharedApplication] delegate];
    
    delegate.isNoNetWork=YES;
}

-(void)viewWillDisappear:(BOOL)animated
{
    [super viewWillDisappear:animated];
    [txtVin resignFirstResponder];//VIN
    [txtTransmission resignFirstResponder];//变
    [txtColor resignFirstResponder];//颜色
    [txtDriveDirection resignFirstResponder];
    [txtDefect_Info resignFirstResponder];//重
    [txtRepair_Info resignFirstResponder];//返
    [txtEngine resignFirstResponder];
    [txtShiftDate  resignFirstResponder];
    [txtBuildDate resignFirstResponder];
    [txtCsn  resignFirstResponder];//生
}

-(void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    
    AppDelegate *delegate=(AppDelegate*)[[UIApplication sharedApplication] delegate];
    
    if (!delegate.isLoadCarList) {
        delegate.isNoNetWork=NO;
        [self getCarList];
//        [self setInitData];
    }
    else
    {
        [self setInitData];
    }
    
//    dispatch_async(dispatch_get_global_queue(0, 0), ^{
//        while (1) {
//            [NSThread sleepForTimeInterval:0.05];
//            
//            if (delegate.isLoadCarList)
//            {
//                dispatch_async(dispatch_get_main_queue(),^{
//                    [self setInitData];
//                });
//                break;
//            }
//            else if (delegate.isNoNetWork)
//            {
//                break;
//            }
//        }
//    });
}

-(void)viewDidAppear:(BOOL)animated
{
    NSDateFormatter  *dateformatter=[[NSDateFormatter alloc] init];
    [dateformatter setDateFormat:@"yyyy-MM-dd"];
    
    NSDate *date1 = [dateformatter dateFromString:txtShiftDate.text];
    NSDate *date2 = [dateformatter dateFromString:txtBuildDate.text];
    
    if ([self.doSth isEqualToString:@"edit"]) {
        [self.datePick1 setDate:date1];
        [self.datePick2 setDate:date2];
    }
}

- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)toInterfaceOrientation {
    if (toInterfaceOrientation == UIInterfaceOrientationLandscapeLeft || toInterfaceOrientation == UIInterfaceOrientationLandscapeRight) {
        return YES;
    }
    return NO;
}


- (BOOL)shouldAutorotate
{
    return YES;
}

- (NSUInteger)supportedInterfaceOrientations
{
    return UIInterfaceOrientationMaskLandscape;
}

-(void)setInitData
{
    NSUserDefaults *userInfo=[NSUserDefaults standardUserDefaults];
    
    self.arrDomainList = [userInfo arrayForKey:@"domainList"];
    self.arrGroupList  = [userInfo arrayForKey:@"groupList"];
    self.arrModelList  = [userInfo arrayForKey:@"modelList"];
    self.arrPhaseList  = [userInfo arrayForKey:@"phaseList"];
    self.arrPlantList  = [userInfo arrayForKey:@"plantList"];
    self.arrSeriesList = [userInfo arrayForKey:@"seriesList"];
    
    //设置选中初始值
    if ([self.doSth isEqualToString:@"add"]) {
        self.currentCar.series=[[((NSArray *)self.arrSeriesList) objectAtIndex:0] objectForKey:@"key"];
        self.currentCar.seriesDesc=[[((NSArray *)self.arrSeriesList) objectAtIndex:0] objectForKey:@"value"];
        
        self.currentCar.model=[[((NSArray *)self.arrModelList) objectAtIndex:0] objectForKey:@"key"];
        self.currentCar.modelDesc=[[((NSArray *)self.arrModelList) objectAtIndex:0] objectForKey:@"value"];
        
        self.currentCar.phase=[[((NSArray *)self.arrPhaseList) objectAtIndex:0] objectForKey:@"key"];
        self.currentCar.phaseDesc=[[((NSArray *)self.arrPhaseList) objectAtIndex:0] objectForKey:@"value"];
        
        self.currentCar.plant=[[((NSArray *)self.arrPlantList) objectAtIndex:0] objectForKey:@"key"];
        self.currentCar.plantDesc=[[((NSArray *)self.arrPlantList) objectAtIndex:0] objectForKey:@"value"];
        
        self.currentCar.domain=[[((NSArray *)self.arrDomainList) objectAtIndex:0] objectForKey:@"key"];
        self.currentCar.domainDesc=[[((NSArray *)self.arrDomainList) objectAtIndex:0] objectForKey:@"value"];
        
        self.currentCar.auditGroup=[[((NSArray *)self.arrGroupList) objectAtIndex:0] objectForKey:@"key"];
        self.currentCar.auditGroupDesc=[[((NSArray *)self.arrGroupList) objectAtIndex:0] objectForKey:@"value"];
        
        self.currentCar.shiftDate=[(NSDictionary *)[[userInfo arrayForKey:@"dateList"] objectAtIndex:0] objectForKey:@"value"];
        self.currentCar.buildDate=[(NSDictionary *)[[userInfo arrayForKey:@"dateList"] objectAtIndex:1] objectForKey:@"value"];
    }
    
    //设置btn初始值
    [btnSeries setTitle:self.currentCar.seriesDesc forState:UIControlStateNormal];
    [btnModel setTitle:self.currentCar.modelDesc forState:UIControlStateNormal];
    [btnPlant setTitle:self.currentCar.plantDesc forState:UIControlStateNormal];
    [btnDomain setTitle:self.currentCar.domainDesc forState:UIControlStateNormal];
    [btnAuditGroup setTitle:self.currentCar.auditGroupDesc forState:UIControlStateNormal];
    [btnPhase setTitle:self.currentCar.phaseDesc forState:UIControlStateNormal];
    
    txtShiftDate.text=self.currentCar.shiftDate;
    txtBuildDate.text=self.currentCar.buildDate;
    
    if ([self.doSth isEqualToString:@"edit"]) {
        txtBuildDate.text=self.currentCar.buildDate;
        txtColor.text=self.currentCar.color;
        txtCsn.text=self.currentCar.csn;
        txtDefect_Info.text=self.currentCar.defect_info;
        txtDriveDirection.text=self.currentCar.drivedirection;
        txtEngine.text=self.currentCar.engine;
        txtRepair_Info.text=self.currentCar.repair_info;
        txtShiftDate.text=self.currentCar.shiftDate;
        txtTransmission.text=self.currentCar.transmission;
        txtVin.text=self.currentCar.vin;
    }
    
    [self.view setNeedsLayout];
}

-(void)initDicList
{
    btnSeries.tag=1001;
    btnModel.tag=1002;
    btnPlant.tag=1003;
    btnDomain.tag=1004;
    btnAuditGroup.tag=1005;
    txtShiftDate.tag=1006;
    txtBuildDate.tag=1007;
    btnPhase.tag=1008;
    txtVin.tag=1009;
    
    txtBuildDate.returnKeyType = UIReturnKeyNext;
    txtColor.returnKeyType = UIReturnKeyNext;
    txtCsn.returnKeyType = UIReturnKeyNext;
    txtDefect_Info.returnKeyType = UIReturnKeyNext;
    txtDriveDirection.returnKeyType = UIReturnKeyNext;
    txtEngine.returnKeyType = UIReturnKeyNext;
    txtRepair_Info.returnKeyType = UIReturnKeyNext;
    txtShiftDate.returnKeyType = UIReturnKeyNext;
    txtTransmission.returnKeyType = UIReturnKeyNext;
    txtVin.returnKeyType = UIReturnKeyNext;
    
    txtBuildDate.delegate = (id<UITextFieldDelegate>)self;
    txtColor.delegate = (id<UITextFieldDelegate>)self;
    txtCsn.delegate = (id<UITextFieldDelegate>)self;
    txtDefect_Info.delegate = (id<UITextFieldDelegate>)self;
    txtDriveDirection.delegate = (id<UITextFieldDelegate>)self;
    txtEngine.delegate = (id<UITextFieldDelegate>)self;
    txtRepair_Info.delegate = (id<UITextFieldDelegate>)self;
    txtShiftDate.delegate = (id<UITextFieldDelegate>)self;
    txtTransmission.delegate = (id<UITextFieldDelegate>)self;
    txtVin.delegate = (id<UITextFieldDelegate>)self;
    
    [txtVin addTarget:self action:@selector(textChange:) forControlEvents:UIControlEventEditingChanged];
    
    if (!self.currentCar) {
        self.currentCar=[[Car alloc] init];
    }
    
    self.arrDomainList = [NSArray array];
    self.arrGroupList  = [NSArray array];
    self.arrModelList  = [NSArray array];
    self.arrPhaseList  = [NSArray array];
    self.arrPlantList  = [NSArray array];
    self.arrSeriesList = [NSArray array];
    self.datePick1      = [[UIDatePicker alloc] init];
    self.datePick1.datePickerMode = UIDatePickerModeDate;
    
    self.datePick2      = [[UIDatePicker alloc] init];
    self.datePick2.datePickerMode = UIDatePickerModeDate;
    
    txtShiftDate.delegate = (id<UITextFieldDelegate>)self;
    txtShiftDate.inputView = self.datePick1;
    
    txtBuildDate.delegate = (id<UITextFieldDelegate>)self;
    txtBuildDate.inputView = self.datePick2;
    
    [self.datePick1 addTarget:self action:@selector(dateDidPicker:) forControlEvents:UIControlEventValueChanged];
    
    [self.datePick2 addTarget:self action:@selector(dateDidPicker:) forControlEvents:UIControlEventValueChanged];
}

-(void)dateDidPicker:(id)sender
{
    UIDatePicker *datePick = (UIDatePicker *)sender==self.datePick1?self.datePick1:self.datePick2;
    
    NSDate * senddate=[datePick date];
    
//    NSCalendar *calendar = [ NSCalendar currentCalendar ];
//    
//    int unit = NSCalendarUnitDay | NSCalendarUnitMonth |  NSCalendarUnitYear ;
//    
//    NSDateComponents *plusdays=[calendar components :unit fromDate : [datePick date] toDate :[ NSDate date ] options : 0 ];
    
//    if (!(plusdays.year>0||plusdays.month>0||plusdays.day>0))
//    {
    NSDateFormatter  *dateformatter=[[NSDateFormatter alloc] init];
    [dateformatter setDateFormat:@"yyyy-MM-dd"];
    
    if (datePick==self.datePick1) {
        txtShiftDate.text=[NSString stringWithFormat:@"%@",[dateformatter stringFromDate:senddate]];
    }
    else
    {
        txtBuildDate.text=[NSString stringWithFormat:@"%@",[dateformatter stringFromDate:senddate]];
    }
//    }
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (void)navRightButtonActionAtTag:(NSUInteger)tag
{
    [super backAction:nil];
}
/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

-(IBAction)chooseConditionAction:(id)sender
{
    if (((UIButton *)sender).tag!=1006&&((UIButton *)sender).tag!=1007) {
        UIButton *btn = (UIButton*)sender;
        ConditionViewController *vc = [[ConditionViewController alloc] init];
        vc.fromVC=@"addcar";
        vc.naviTitle = btn.titleLabel.text;
        vc.paramsArr = [NSArray array];
        switch (((UIButton *)sender).tag) {
            case 1001:
                vc.paramsArr = self.arrSeriesList;
                break;
            case 1002:
                vc.paramsArr = self.arrModelList;
                break;
            case 1003:
                vc.paramsArr = self.arrPlantList;
                break;
            case 1004:
                vc.paramsArr = self.arrDomainList;
                break;
            case 1005:
                vc.paramsArr = self.arrGroupList;
                break;
            case 1008:
                vc.paramsArr = self.arrPhaseList;
                break;
            default:
                break;
        }
        
        [self presentViewControllerInSmallRect:vc];
        
        vc.setText=^(NSString *key,NSString *value)
        {
            //设置选中值
            switch (((UIButton *)sender).tag) {
                case 1001:
                    self.currentCar.series=key;
                    self.currentCar.seriesDesc=value;
                    break;
                case 1002:
                    self.currentCar.model=key;
                    self.currentCar.modelDesc=value;
                    break;
                case 1003:
                    self.currentCar.plant=key;
                    self.currentCar.plantDesc=value;
                    break;
                case 1004:
                    self.currentCar.domain=key;
                    self.currentCar.domainDesc=value;
                    break;
                case 1005:
                    self.currentCar.auditGroup=key;
                    self.currentCar.auditGroupDesc=value;
                    break;
                case 1008:
                    self.currentCar.phase=key;
                    self.currentCar.phaseDesc=value;
                    break;
                default:
                    break;
            }
            
            UIButton *btnSender = (UIButton *)sender;
            
            [btnSender setTitle:value forState:UIControlStateNormal];
        };
    }
//    else
//    {
//        UITextField *txt=(UITextField *)sender;
//        
//        txt.delegate = (id<UITextFieldDelegate>)self;
//        
//        txt.inputView = self.datePick;
//        
//        switch (txt.tag) {
//            case 1006:
//                
//                break;
//            case 1007:
//                
//                break;
//            default:
//                break;
//
//        }
//    }
}

//扫描条形码获取VIN
-(IBAction)getVinStr:(id)sender
{
    GetVinViewController * getVinVC = [[GetVinViewController alloc]init];//扫描条形码二维码VC
    getVinVC.doSth=@"getVIN";
    getVinVC.getVinStr=^(NSString *vinStr){
        NSLog(@"%@",vinStr);
        txtVin.text = vinStr;
    };
    
    [self presentViewControllerInFullRect:getVinVC];
}

//扫描条形码获取TPS
-(IBAction)getTPSStr:(id)sender
{
    GetVinViewController * getVinVC = [[GetVinViewController alloc]init];//扫描条形码二维码VC
    getVinVC.doSth=@"getTPS";
    getVinVC.getVinStr=^(NSString *vinStr){
        NSLog(@"%@",vinStr);
        
        NSString *csnStr=[vinStr substringToIndex:8];
        
        txtCsn.text = csnStr;
    };
    
    [self presentViewControllerInFullRect:getVinVC];
}

-(NSString *)getStr:(NSString *)str
{
    return str?str:@"";
}

//保存车辆信息
-(IBAction)saveAction:(id)sender
{   
    self.currentCar.vin            = txtVin.text;//VIN
    self.currentCar.transmission  = txtTransmission.text;//变速箱
    self.currentCar.color          = txtColor.text;//颜色
    self.currentCar.drivedirection = txtDriveDirection.text;//驾驶方向
    self.currentCar.defect_info         = txtDefect_Info.text;//重点缺陷
    self.currentCar.repair_info     = txtRepair_Info.text;//返修信息
    self.currentCar.engine          = txtEngine.text;//引擎
    self.currentCar.shiftDate      = txtShiftDate.text;//检查日期
    self.currentCar.buildDate    = txtBuildDate.text;//生产日期
    self.currentCar.csn     = txtCsn.text;//生产序号
    
    NSMutableArray *keyArr=[NSMutableArray arrayWithObjects:@"plantList",@"domainList",@"auditGroupList",@"shiftDate",@"buildDate",@"seriesList",@"modelList",@"vin",@"csn",@"phaseList",@"engine",@"transmission",@"color",@"drivedirection",@"defect_info",@"repair_info", nil];
    NSMutableArray *valueArr=[NSMutableArray arrayWithObjects:[self getStr:self.currentCar.plant],[self getStr:self.currentCar.domain],[self getStr:self.currentCar.auditGroup],[self getStr:self.currentCar.shiftDate],[self getStr:self.currentCar.buildDate],[self getStr:self.currentCar.series],[self getStr:self.currentCar.model],[self getStr:self.currentCar.vin],[self getStr:self.currentCar.csn],[self getStr:self.currentCar.phase],[self getStr:self.currentCar.engine],[self getStr:self.currentCar.transmission],[self getStr:self.currentCar.color],[self getStr:self.currentCar.drivedirection],[self getStr:self.currentCar.defect_info],[self getStr:self.currentCar.repair_info],nil];
    
    if ([self.doSth isEqualToString:@"edit"]) {
        [keyArr addObject:@"vehicleId"];
        [valueArr addObject:self.currentCar.vehicleId];
    }
    
    [gAlert showLoading:nil delegate:nil];
    [CommunicateWithService communicateWithService:keyArr value:valueArr apiName:@"vhcSave.do" finishSelector:@selector(addNewCarFinished:) failSelector:@selector(addNewCarFailed:) delegateObj:self];
}

//请求服务器成功
-(void)addNewCarFinished:(ASIFormDataRequest *)request
{
    [gAlert dismiss];
    if (request.responseStatusCode == 400) {
        NSLog(@"Invalid code");
    } else if (request.responseStatusCode == 403) {
        NSLog(@"Code already used");
    } else if (request.responseStatusCode == 200) {
        NSDictionary *strDic=[CommunicateWithService getDataDic:request.responseString];//解析json To dic
        
        NSString *flag=[strDic objectForKey:@"resultCode"];//服务器返回代码
        
        NSString *msg=[strDic objectForKey:@"resultValue"];//服务器返回提示消息
        
        NSDictionary *strDicData=(NSDictionary *)[strDic objectForKey:@"resultData"];//服务器返回dic
        
        if ([flag isEqualToString:@"1001"]) {
            if ([self.doSth isEqualToString:@"edit"]) {
                if (self.editCar) {
                    self.editCar(self.currentCar);
                    [self dismissViewControllerAnimated:YES completion:nil];
                }
            }
            else
            {
                self.currentCar.vehicleId=[strDicData objectForKey:@"vehicleId"];
                
                if (self.addCar) {
                    self.addCar(self.currentCar);
                    [self dismissViewControllerAnimated:YES completion:nil];
                }
            }
        }
        else if([flag isEqualToString:@"1002"]) {
            [gAlert show:msg inView:self.view delegate:nil];
        }
    }
}

//请求服务器失败
-(void)addNewCarFailed:(ASIFormDataRequest *)request
{
    [gAlert dismiss];
    [NetworkCheck checkNetwork:self];//检查网络
}

- (void)keyboardWasShown:(NSNotification*)aNotification
{
    if (_selectedTxt!= txtVin && _selectedTxt!=txtBuildDate && _selectedTxt!=txtShiftDate) {
        [UIView animateWithDuration:.8f animations:^{
            self.view.transform = CGAffineTransformMakeTranslation(0,-240);
        }];
    }
}

- (void)keyboardWillBeHidden:(NSNotification*)aNotification
{
    [UIView animateWithDuration:.8f animations:^{
        self.view.transform = CGAffineTransformIdentity;
    }];
}

- (BOOL)textFieldShouldReturn:(UITextField *)textField {
    if(textField.returnKeyType == UIReturnKeyNext){
        [textField resignFirstResponder];
    }
    return YES;
}

- (void)textFieldDidBeginEditing:(UITextField *)textField
{
    _selectedTxt = textField;
    
    [textField becomeFirstResponder];
}

- (void)textFieldDidEndEditing:(UITextField *)textField
{
    [textField resignFirstResponder];
}

- (void)textChange:(UITextField *)textField
{
    textField.text = [textField.text stringByReplacingOccurrencesOfString:@" " withString:@""];
    
    if (textField.text.length>17) {
        textField.text = [textField.text substringToIndex:17];
        
        [gAlert show:@"VIN号不能超过17位噢" inView:self.view delegate:nil];
    }
    
    textField.text = [textField.text uppercaseString];
}

-(void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
{
    [txtVin resignFirstResponder];//VIN
    [txtTransmission resignFirstResponder];//变
    [txtColor resignFirstResponder];//颜色
    [txtDriveDirection resignFirstResponder];
    [txtDefect_Info resignFirstResponder];//重
    [txtRepair_Info resignFirstResponder];//返
    [txtEngine resignFirstResponder];
    [txtShiftDate  resignFirstResponder];
    [txtBuildDate resignFirstResponder];
    [txtCsn  resignFirstResponder];//生
}

@end
